package zhttp

import (
	"context"
	"encoding/json"
	"io"
	"net/http"

	"gitee.com/shijingzhao/go-frame/reflex"
	"gitee.com/shijingzhao/go-frame/zlog"
)

// ParamsAnalysis 参数处理
func ParamsAnalysis(r *http.Request, rq interface{}) {
	if err := r.ParseForm(); err != nil {
		return
	}

	params := make(map[string]interface{}, len(r.Form))
	for name := range r.Form {
		formValue := r.Form.Get(name)
		if len(formValue) > 0 {
			params[name] = formValue
		}
	}

	_ = reflex.MapToStruct(params, rq)
}

func JsonAnalysis(r *http.Request, rq interface{}) {
	body := make([]byte, r.ContentLength)

	// 调用 Read 方法读取请求实体并将返回内容存放到上面创建的字节切片
	if _, err := r.Body.Read(body); err != nil && err != io.EOF {
		zlog.NewAppError(context.TODO()).Error("http JsonAnalysis r.Body.Read", zlog.String("err", err.Error()))
		return
	}

	if err := json.Unmarshal(body, rq); err != nil {
		zlog.NewAppError(context.TODO()).Error("http JsonAnalysis json.Unmarshal", zlog.String("err", err.Error()), zlog.Byte("body", body))
		return
	}
}
